package serial_handle

import (
	"data-system/models"
	"data-system/tools"
	"fmt"
	"log"

	"github.com/spf13/cast"
)

type SerialNumberCtx struct {
	models.SerialHandleCtx
}

func NewSerialNumberCtx(ctx models.SerialHandleCtx) (SerialHandler, error) {
	return &SerialNumberCtx{SerialHandleCtx: ctx}, nil
}

// Encode Excel数据 转 DB数据
func (ctx *SerialNumberCtx) Encode() (models.SerialHandleCtx, error) {
	if ctx.ExcelRow == nil {
		msg := fmt.Sprintf("【序列化-number】【%v - %v - %v】行数据不能为空", ctx.Column.NodeType, ctx.Column.TbField, ctx.Column.Type)
		log.Printf(msg)
		return ctx.SerialHandleCtx, fmt.Errorf(msg)
	}
	if ctx.Column.Required && len(ctx.ExcelRow.Row[ctx.Column.TbField]) == 0 {
		msg := fmt.Sprintf("【序列化-number】【%v - %v - %v】字段值不能为空", ctx.Column.NodeType, ctx.Column.TbField, ctx.Column.Type)
		log.Printf(msg)
		return ctx.SerialHandleCtx, fmt.Errorf(msg)
	}
	if len(ctx.ExcelRow.Row[ctx.Column.TbField]) > 0 {
		excelOriginValue := cast.ToString(ctx.ExcelRow.Row[ctx.Column.TbField])
		handleValue, err := tools.StringToInt64(excelOriginValue)
		if err != nil {
			msg := fmt.Sprintf("【序列化-number】【%v - %v - %v】转number失败：value=%v", ctx.Column.NodeType, ctx.Column.TbField, ctx.Column.Type, excelOriginValue)
			log.Printf(msg)
			return ctx.SerialHandleCtx, fmt.Errorf(msg)
		}
		ctx.ResultData = handleValue
	}
	return ctx.SerialHandleCtx, nil
}

// Decode DB数据 转 Excel数据
func (ctx *SerialNumberCtx) Decode() (models.SerialHandleCtx, error) {
	if ctx.DbRow == nil {
		msg := fmt.Sprintf("【反序列化-number】【%v - %v - %v】行数据不能为空", ctx.Column.NodeType, ctx.Column.TbField, ctx.Column.Type)
		log.Println(msg)
		return ctx.SerialHandleCtx, fmt.Errorf(msg)
	}
	if ctx.Column.Required && ctx.DbRow.Data[ctx.Column.Name] == nil {
		msg := fmt.Sprintf("【反序列化-number】【%v - %v - %v】字段值不能为空", ctx.Column.NodeType, ctx.Column.TbField, ctx.Column.Type)
		log.Println(msg)
		return ctx.SerialHandleCtx, fmt.Errorf(msg)
	}
	ctx.ResultData = ""
	if ctx.DbRow.Data[ctx.Column.Name] != nil {
		ctx.ResultData = cast.ToString(ctx.DbRow.Data[ctx.Column.Name])
	}
	return ctx.SerialHandleCtx, nil
}
